import { toString } from './utils'
export default class Jquery {
    static fn = Jquery.prototype
    public select(selector, context) {

    }
    public isPlainObject(val: any): boolean {
        if (toString.call(val) !== '[object Object]') {
            return false;
        }

        var prototype = Object.getPrototypeOf(val);
        return prototype === null || prototype === Object.prototype;
    }

    public extend(...args: any) {
        let target = args[0] || {}
        let i = 1
        let deep = false
        let length = args.length
        if (typeof target === "boolean") {
            deep = target;
            // 如果第一个为布尔值，则目标对象改为第二个
            target = args[i] || {};
            i++;
        }
        if (typeof target !== "object" && typeof target !== "function") {
            target = {};
        }
        // 如果只传了一个参数，那么target就是jquery本身，可以用这个方法为jq添加方法
        if (i === length) {
            target = this;
            i--;
        }

        // 对被合并参数进行遍历
        for (; i < length; i++) {
            // 只处理非null非undefinded的值
            let options: any, copyIsArray
            if ((options = arguments[i]) != null) {

                // Extend the base object
                for (let name in options) {
                    let copy = options[name];

                    // 防止原型链方法合并入target
                    // 防止死循环
                    if (name === "__proto__" || target === copy) {
                        continue;
                    }

                    // 如果要合并普通对象或数组，则使用递归
                    if (deep && copy && (this.isPlainObject(copy) ||
                        (copyIsArray = Array.isArray(copy)))) {
                        let src = target[name];
                        let clone
                        // 确保源值的类型正确
                        if (copyIsArray && !Array.isArray(src)) {
                            clone = [];
                        } else if (!copyIsArray && !this.isPlainObject(src)) {
                            clone = {};
                        } else {
                            clone = src;
                        }
                        copyIsArray = false;

                        // Never move original objects, clone them
                        target[name] = this.extend(deep, clone, copy);

                        // Don't bring in undefined values
                    } else if (copy !== undefined) {
                        target[name] = copy;
                    }
                }
            }
        }
        return target
    }
}